<script setup>
import { onMounted, reactive, ref } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import EditEndUserdevice from './EditEndUserdevice.vue'
import BangDingEndUserdevice from './BangDingEndUserdevice.vue'
// import PiInventorydevice from './PiInventorydevice.vue'
// import ChuInventorydevice from './ChuInventorydevice.vue'
import CdkeyPanel from './CdkeyPanel.vue'
import { equipmentType, endDropDownapi, getEndUserdeviceapi, getEndUserdevicelike, editequipmentStatus, endReturn, InventoryFile, delInventory, adminResetPassword, editaccountNonLocked } from '../../api/api'
import data from "@/untils/address/states.json"
import { readFile } from "../../untils/importfile/importfile"
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
import { Decrypt, Encrypt } from '../../untils/passjs/security'
onMounted(() => {
    getEndUserDevice()
    // getequipmentType()
    getendDropDown()
})
// 定义的头部输入框的数据
let topdata = ref({
    equipmentName: "",
    equipmentNumber: '',
    // equipmentType: '',
    userId: null,
    onlineStatus: null,
    equipmentStatus: null,
    timevalue: "",
    time: ""
})
// let equipmentTypeList = ref([])
// async function getequipmentType() {
//     let res = await equipmentType()
//     console.log(res);
//     equipmentTypeList.value = res.data
// }
let userIdList = ref([])
async function getendDropDown() {
    let res = await endDropDownapi()
    console.log(res);
    userIdList.value = res.data
}
// 表格数据
let tableData = ref([])
// 获取管理员管理的数据
async function getEndUserDevice() {
    let data = await getEndUserdeviceapi(page.value, pageSize.value)
    if (data.code == 200) {
        total.value = data.total
        tableData.value = data.rows
    }
}
// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}

//    // 删除
let inventoryStatus = ref(null)
let dianjiid = ref(0)
const dialogVisible = ref(false)
function returnHandler(val) {
    dianjiid.value = val.equipmentId
    dialogVisible.value = true
}
function cancelfun(){
    inventoryStatus.value = null
    dialogVisible.value = false
}
async function yesdel() {
    console.log(inventoryStatus.value);
    console.log(dianjiid.value);
    if(inventoryStatus.value == null){
        ElMessage.warning("please select inventory status")
        return;
    }
    let requestData = {
        equipmentId: dianjiid.value,
        inventoryStatus: inventoryStatus.value
    }
    let res = await endReturn(requestData)
    console.log("del", res);
    if (res.code == 200) {
        inventoryStatus.value = null
        ElMessage.success(res.msg)
        getEndUserDevice()
        dialogVisible.value = false
    }
}
// 遮罩层
let dialogFormVisible = ref(false)
// 定义 是添加还是编辑的字符串
let changeType = ref("")
//  传递参数
let formlist = reactive({})
function add() {
    // tableData.value = []
    // Object.assign(formlist, {
    //     // 用户名、昵称、密码、邮箱、手机号、性别(0,1)、区域(国家/洲(省))、地址(非必填)、用户等级(1-5)
    //     equipmentName: "",
    //     equipmentNumber: "",
    //     equipmentModel: "",
    //     equipmentType: null,
    //     inventoryStatus: null,
    //     type: "新增",
    // })
    // console.log(formlist);
    //  //点击添加按钮
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'
}
function edit(index, row) {
    Object.assign(formlist, {
        equipmentId: row.equipmentId,
        equipmentName: row.equipmentName,
        equipmentNumber: row.equipmentNumber,
        equipmentModel: row.equipmentModel,
        type: "修改",
    })
    console.log(index, row);
    //  //点击编辑按钮
    //  //把row数据赋值给formlist
    // formlist = row
    // console.log(formlist);
    //  //让changeType 标识 为update
    changeType.value = "update"
    //  //让dialogFormVisible显示
    dialogFormVisible.value = true
}
//     // 子传父的事件，关闭遮罩层
function closechange() {
    dialogFormVisible.value = false
    getEndUserDevice()
}
function closechangepi() {
    PidialogFormVisible.value = false
    getEndUserDevice()
}
let BangdialogFormVisible = ref(false)
function closechangeBang() {
    BangdialogFormVisible.value = false
    getEndUserDevice()
}
async function adminlike() {
    console.log("模糊查询操作");
    isSearching.value = true
    let timeType = 0;
    const dateObj = new Date(topdata.value.timevalue);
    const year = dateObj.getFullYear(); // 2025
    const month = dateObj.getMonth() + 1; // 7
    const day = dateObj.getDate(); // 29
    let requesttime = ""
    if (topdata.value.time == 'year') {
        timeType = 6
        // yyyy-MM-dd HH:mm:ss
        requesttime = `${year}-01-01 00:00:00`
    }
    if (topdata.value.time == 'month') {
        timeType = 5
        if (month.toString().length == 1) {
            requesttime = `${year}-0${month}-01 00:00:00`
        } else {
            requesttime = `${year}-${month}-01 00:00:00`
        }
    }
    if (topdata.value.time == 'day') {
        timeType = 4
        let monthd = ''
        let dayd = ''
        if (month.toString().length == 1) {
            monthd = `0${month}`
        }
        if (day.toString().length == 1) {
            dayd = `0${day}`
        } else {
            dayd = day
        }
        requesttime = `${year}-${monthd}-${dayd} 00:00:00`
    }
    topdata.value = {
        ...topdata.value, // 保留其他字段
        timevalue: requesttime // 仅更新 timevalue
    }
    // if(topdata.value.equipmentName == '' || topdata.value.equipmentNumber == '' || topdata.value.equipmentType == '' || topdata.value.equipmentStatus == null || topdata.value.onlineStatus == null || timeType == null || topdata.value.timevalue == ''){
    //     ElMessage.error("请输入查询信息")
    //     return;
    // }
    let res = await getEndUserdevicelike(topdata.value.equipmentName, topdata.value.equipmentNumber, topdata.value.userId, topdata.value.equipmentStatus, topdata.value.onlineStatus, timeType, topdata.value.timevalue, page.value, pageSize.value)
    console.log(res, "like查询");
    if (res.code == 200) {
        tableData.value = res.rows
        if (res.rows.length == 0) {
            return;
        }
        total.value = res.total

    }
}
let isSearching = ref(false)
function cancel() {
    console.log("重置操作");
    isSearching.value = false
    topdata.value = {
        equipmentName: "",
        equipmentNumber: '',
        // equipmentType: '',
        userId: '',
        onlineStatus: null,
        equipmentStatus: null,
        timevalue: "",
        time: ""
    }
    page.value = 1
    getEndUserDevice()
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    // getEndUserDevice()
    if (isSearching.value) {
        await adminlike()
    } else {
        // 否则调用普通分页API
        getEndUserDevice()
    }
}
let selectedFile = ref(null); // 保存用户选择的文件
function importxlsx(file) {
    console.log("导入");
    // // 获取上传excel的文件数据
    // if (!file) {
    //     console.error("没有选择文件！");
    //     return;
    // }
    // selectedFile.value = file.raw;
    // console.log("文件已选择:", selectedFile.value);
}
// async function configHandler() {
//     console.log(selectedFile.value);
//     if (selectedFile.value == null) {
//         ElMessage.error('Please select the file to upload')
//         return;
//     }
//      const formData = new FormData();
//     formData.append('file', selectedFile.value);
//     let res = await InventoryFile(formData)
//     console.log(res);
//     if(res.code == 200){
//         if(res.data.length == 0){
//             ElMessage.success(res.msg)
//             open.value = false
//             getEndUserDevice()
//         }else{
//             res.data.forEach(item=>{
//                 ElMessage.success(item)
//             })
//         }
//     }else{
//         ElMessage.error(res.msg)
//     }
// }
// function handleImport() {
//     open.value = true
// }
// let open = ref(false)

// function handleFileSuccess(response, file, fileList) {
//   upload.value.open = false
// }
// let upload = ref(null)
// function importTemplate() {
//     window.location.href = '/新建 XLSX 工作表 - 模版.xlsx';
// }
// let PidialogFormVisible = ref(false)
// function clearSelectedFile() {
//     console.log("清除操作");
//     if (upload.value) {
//         upload.value.clearFiles();
//         selectedFile.value = null;
//         console.log("文件已清除 selectedFile:", selectedFile.value);
//     } else {
//         console.error("el-upload 实例未找到！");
//     }
// }
function Bangding() {
    BangdialogFormVisible.value = true
}
import lvdeng from "../../assets/images/lvdeng.png"
import hongdengjingshi from "../../assets/images/hongdengjingshi.png"
async function changeswitch(equipmentId, equipmentStatus) {
    console.log(equipmentId, equipmentStatus);
    if (equipmentStatus == 0) {
        equipmentStatus = 1
    } else {
        equipmentStatus = 0
    }
    console.log(equipmentId, equipmentStatus);
    let res = await editequipmentStatus({ equipmentId: equipmentId, equipmentStatus: equipmentStatus })
    console.log(res);
    if (res.code == 200) {
        getEndUserDevice()
    }

}
let PaneldialogFormVisible = ref(false)
function closePanelFun(){
   PaneldialogFormVisible.value = false
   getEndUserDevice()
   equipmentIdvalue.value= null
}
let equipmentIdvalue = ref(null)
function activaopen(row){
    PaneldialogFormVisible.value = true
    console.log(row.equipmentId);
    equipmentIdvalue.value = row.equipmentId
}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; // 如果有 *:*:* 权限，直接返回 true
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Inventory equipment</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 设备名称 -->
                    <div class="select">
                        <el-input v-model="topdata.equipmentName" class="inp" style="width: 190px"
                            placeholder="Enter equipment name">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 设备编号 -->
                    <div class="select">
                        <el-input v-model="topdata.equipmentNumber" class="inp" style="width: 190px"
                            placeholder="Enter equipment code">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <!-- 设备类型 -->
                    <!-- <div class="select">
                        <el-select style="width: 160px" placeholder="equipmentType" v-model="topdata.equipmentType"
                            clearable>
                            <el-option :label="item.name" :value="item.number" v-for="item in equipmentTypeList" />
                        </el-select>
                    </div> -->
                    <!-- 终端用户id -->
                    <div class="select">
                        <el-select style="width: 190px" placeholder="please select end user" v-model="topdata.userId">
                            <el-option :label="item.nickname" :value="item.userId" v-for="item in userIdList" />
                        </el-select>
                    </div>
                    <!-- 在线状态 -->
                    <div class="select">
                        <el-select style="width: 220px" placeholder="please select Online status" v-model="topdata.onlineStatus">
                            <el-option label="online" :value="0" />
                            <el-option label="offline" :value="1" />
                        </el-select>
                    </div>
                    <!-- 设备状态 -->
                    <div class="select">
                        <el-select style="width: 250px" placeholder="please select equipment Status" v-model="topdata.equipmentStatus">
                            <el-option label="normal" :value="0" />
                            <el-option label="disable" :value="1" />
                        </el-select>
                    </div>
                    <!-- 购买时间 -->
                    <div class="select">
                        <el-select style="width: 200px" placeholder="please select storage time" v-model="topdata.time">
                            <el-option label="year" value="year" />
                            <el-option label="month" value="month" />
                            <el-option label="day" value="day" />
                        </el-select>
                    </div>
                    <div class="select">
                        <!-- 年 -->
                        <el-date-picker v-model="topdata.timevalue" type="year" placeholder="Pick a year"
                            v-if="topdata.time == 'year'" />
                        <!-- 月 -->
                        <el-date-picker v-model="topdata.timevalue" type="month" placeholder="Pick a month"
                            v-if="topdata.time == 'month'" />
                        <!-- 日 -->
                        <el-date-picker v-model="topdata.timevalue" type="date" placeholder="Pick a day"
                            v-if="topdata.time == 'day'" />
                    </div>
                    <el-button type="primary" @click="adminlike">query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp">
                    <div class="export-excel">
                        <el-button style="width: 180px" type="primary" @click="Bangding()" v-if="hasPermission('equipment:end:bind')">
                            <el-icon style="margin-right: 5px;">
                                <FolderAdd />
                            </el-icon>Bind end users
                        </el-button>
                        <!-- <el-dropdown style="cursor: pointer;margin: 0 20px;">
                            <el-button style="width: 180px" type="primary">
                                <el-icon style="margin-right: 5px;">
                                    <FolderAdd />
                                </el-icon>Ratch put in storage
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu style="width: 180px;">
                                    <el-dropdown-item command="viewDetails"
                                        @click="handleImport">file Import</el-dropdown-item>
                                    <el-dropdown-item command="viewDetails"
                                        @click="() => PidialogFormVisible = true">batch Import</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown> -->
                        <!-- <el-button style="width: 120px" type="primary" @click="() => ChudialogFormVisible = true">
                            <el-icon style="margin-right: 5px;">
                                <FolderAdd />
                            </el-icon>Outbound
                        </el-button> -->
                    </div>
                </div>
                <div class="tab">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true" v-if="hasPermission('equipment:end:query')">
                        <el-table-column width="55"></el-table-column>
                        <el-table-column property="equipmentName" label="name" />
                        <el-table-column property="equipmentNumber" label="code" />
                        <el-table-column property="equipmentModel" label="model" />
                        <el-table-column property="equipmentType" label="type">
                            <template #default="scope">
                                <span>{{ scope.row.equipmentType == 1 ? 'Battery' : 'WaterPump' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="onlineStatus" label="online Status">
                            <template #default="scope">
                                <div style="display: flex;align-items: center;">
                                    <img :src="scope.row.onlineStatus == 0 ? lvdeng : hongdengjingshi"
                                        style="width: 20px;height: 20px" alt="">
                                    <!-- <span>{{ scope.row.onlineStatus == 0 ? '在线' : '离线' }}</span> -->
                                    <el-tag :type="scope.row.onlineStatus == 0 ? 'success' : 'info'">{{
                                        scope.row.onlineStatus == 0 ? 'online' : 'offline' }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column property="equipmentStatus" label="equipment Status">
                            <template #default="scope">
                                <template v-if="scope.row.optStatus">
                                    <!-- <span>{{ scope.row.equipmentStatus == 0 ? '正常' : '禁用' }}</span> -->
                                    <el-switch :modelValue="switchFlag(scope.row.equipmentStatus)" active-text="enable"
                                        inline-prompt inactive-text="disable"
                                        @click="changeswitch(scope.row.equipmentId, scope.row.equipmentStatus)"
                                        class="el-switch">
                                    </el-switch>
                                </template>
                                <template v-else>
                                    {{ scope.row.enabled ? 'disable' : 'enable' }}
                                </template>

                            </template>
                        </el-table-column>
                        <el-table-column property="storageTime" label="storage time" />
                        <el-table-column property="userNiceName" label="End user name" />
                        <!-- <el-table-column property="gender" label="gender">
                            <template #default="scope">
                                <span>{{ scope.row.gender == 1 ? 'male' : 'female' }}</span>
                            </template>
                        </el-table-column> -->

                        <!-- <el-table-column property="accountNonLocked" label="Lock status">
                            <template #default="scope">
                                <el-switch :modelValue="switchFlag(scope.row.accountNonLocked)" active-text="enable"
                                    inline-prompt inactive-text="disable"
                                    @click="switchchange(scope.row.userId, scope.row.accountNonLocked)"
                                    class="el-switch">
                                </el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column property="enabled" label="Startup status">
                            <template #default="scope">
                                <el-switch :modelValue="switchFlag(scope.row.enabled)" active-text="enable"
                                    inline-prompt inactive-text="disable"
                                    @click="switchchangeenabled(scope.row.userId, scope.row.enabled)" class="el-switch">
                                </el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column property="userLevel" label="user level">
                            <template #default="scope">
                                <span>{{ {
                                    0: 'T0', 1: 'T1', 2: 'T2', 3: 'T3', 4: 'T4', 5:
                                        'T5'
                                }[scope.row.userLevel] }}</span>
                            </template>
                        </el-table-column> -->
                        <el-table-column property="name" label="operate" width="300">
                            <template #default="scope">
                                <span class="more-button" @click="edit(scope.$index, scope.row)"
                                    style="cursor: pointer;" v-show="scope.row.optStatus" v-if="hasPermission('equipment:end:edit')">
                                    edit
                                </span>
                                <!-- <span class="more-button" @click="del(scope.row)" style="cursor: pointer;" v-show="scope.row.optStatus">
                                    delete
                                </span> -->
                                <!-- 添加“更多”按钮及下拉菜单 -->
                                <el-dropdown style="cursor: pointer;" v-show="scope.row.optStatus">
                                    <span class="more-button">
                                        more
                                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="viewDetails" @click="activaopen(scope.row)">activation code</el-dropdown-item>
                                            <el-dropdown-item command="viewDetails"
                                                @click="returnHandler(scope.row)" v-if="hasPermission('equipment:end:return')" >return</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                                <!-- <el-dialog v-model="passwordVisible" title="reset password" width="500"
                                    modal-class="custom-modal" @close="passwordVisible = false">
                                    <span>please enter {{ currentUser.username }} new password:</span>
                                    <br>
                                    <el-form :model="resetForm" :rules="rulesobj" ref="resetFormRef">
                                        <el-form-item label="" prop="newpass">
                                            <el-input v-model="resetForm.newpass" type="password" maxlength="16"
                                                minlength="8" auto-complete="off" placeholder="password"></el-input>
                                        </el-form-item>
                                    </el-form>
                                    <template #footer>
                                        <div class="dialog-footer">
                                            <el-button @click="passwordVisible = false">cancel</el-button>
                                            <el-button type="primary" @click="reactpass(scope.row)">sure</el-button>
                                        </div>
                                    </template>
                                </el-dialog> -->
                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                </div>
                <el-dialog v-model="dialogVisible" title="return" width="500">
                    <el-select placeholder="please select inventory status" v-model="inventoryStatus">
                        <el-option label="New_State" :value="0" />
                        <el-option label="Maintenance_State" :value="1" />
                        <el-option label="Return_State" :value="2" />
                    </el-select>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="cancelfun()">cancel</el-button>
                            <el-button type="primary" @click="yesdel()">
                                sure
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <EditEndUserdevice :dialogFormVisible="dialogFormVisible" :changeType="changeType"
                    v-model:formlist="formlist" @close="closechange"></EditEndUserdevice>
                <!-- <PiInventorydevice :PidialogFormVisible="PidialogFormVisible" @closepi="closechangepi" -->
                <!-- :changeType="changeType"> -->
                <!-- </PiInventorydevice> -->
                <BangDingEndUserdevice :BangdialogFormVisible="BangdialogFormVisible" @closeBang="closechangeBang">
                </BangDingEndUserdevice>
                <CdkeyPanel :PaneldialogFormVisible="PaneldialogFormVisible" :equipmentIdvalue='equipmentIdvalue' @closePanel="closePanelFun"></CdkeyPanel>
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
             .one {
                margin: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 12px;
                align-items: center;
                padding: 10px;
            }
            .select {
                display: flex;
                align-items: center;
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }

            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }

    .demo-datetime-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
        justify-content: space-around;
        align-items: stretch;
    }

    .demo-datetime-picker .block {
        padding: 30px 0;
        text-align: center;
    }

    .line {
        width: 1px;
        background-color: var(--el-border-color);
    }

    .el-switch {
        --el-switch-on-color: #45d585;
    }
}
</style>